import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { ResultData } from '@/api/types';
import { ResultEnum } from '@/enums/httpEnum';
import { GlobalStore } from '@/stores/global';
import router from '@/routers';
import { Notification } from '@arco-design/web-vue';
import { DEFAULT_ROUTE_NAME, LOGIN_ROUTE_NAME } from '@/routers/constants';
import { encode } from 'js-base64';

const config = {
	// 默认地址请求地址，可在 .env.*** 文件中修改
	baseURL: import.meta.env.VITE_APP_BASE_API as string,
	// 设置超时时间（30s）
	timeout: ResultEnum.TIMEOUT as number,
	// 跨域时候允许携带凭证
	withCredentials: true,
};

class RequestHttp {
	service: AxiosInstance;
	public constructor(config: AxiosRequestConfig) {
		// 实例化axios
		this.service = axios.create(config);
		/**
		 * @description 请求拦截器
		 * 客户端发送请求 -> [请求拦截器] -> 服务器
		 * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
		 */
		this.service.interceptors.request.use(
			(config: InternalAxiosRequestConfig) => {
				const globalStore = GlobalStore();
				// TODO loading
				const token = globalStore.token;
				if (config.headers && typeof config.headers?.set === 'function') config.headers.Authorization = 'Bearer ' + token;
				return config;
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);

		/**
		 * @description 响应拦截器
		 *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
		 */
		this.service.interceptors.response.use(
			(response: AxiosResponse) => {
				const { data } = response;
				const globalStore = GlobalStore();
				// TODO close loading
				// * 登陆失效（code == 401）
				if (data.code === ResultEnum.OVERDUE) {
					globalStore.resetUserInfo();
					const redirectPath =
						globalStore.currentRoute === '' || globalStore.currentRoute === 'undefined' ? DEFAULT_ROUTE_NAME : globalStore.currentRoute;
					router.replace({ name: LOGIN_ROUTE_NAME, query: { redirect: encode(redirectPath) } }).then((r) => {
						Notification.error({
							title: '登录超时',
							content: '登录超时，请重新登陆',
						});
					});
					return Promise.reject(data);
				}
				// * 全局错误信息拦截
				if (data.code !== ResultEnum.SUCCESS) {
					Notification.error({
						title: '请求失败',
						content: data.msg,
					});
					return Promise.reject(data);
				}
				// * 成功请求（在页面上除非特殊情况，否则不用在页面处理失败逻辑）
				return data;
			},
			async (error: AxiosError) => {
				const { response } = error;
				// TODO close loading
				// 请求超时 && 网络错误单独判断，没有 response
				if (error.message.indexOf('timeout') !== -1) {
					Notification.error({
						title: '系统异常',
						content: '请求超时！请您稍后重试',
					});
				}
				if (error.message.indexOf('Network Error') !== -1) {
					Notification.error({
						title: '系统异常',
						content: '网络错误！请您稍后重试',
					});
				}
				// TODO 根据响应的错误状态码，做不同的处理
				// 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
				if (!window.navigator.onLine) await router.replace('/500');
				return Promise.reject(error);
			}
		);
	}

	// * 常用请求方法封装
	get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.get(url, { params, ..._object });
	}
	post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.post(url, params, _object);
	}
	put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.put(url, params, _object);
	}
	delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
		return this.service.delete(url, { params, ..._object });
	}
	download(url: string, params?: object, _object = {}): Promise<BlobPart> {
		return this.service.post(url, params, { ..._object, responseType: 'blob' });
	}
	customGet(url: string, params?: any, _object = {}): Promise<any> {
		return axios.get(url, { params, ..._object });
	}
}

export default new RequestHttp(config);
